package cloudjunit;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.WorkflowWorker;

public class WorkflowHost
{

    private static final String DECISION_TASK_LIST = "UnitTestWorkflow";
    
    public static void main(String[] args) throws Exception
    {
    	boolean shouldReadInput =  args.length == 0 || !args[0].equalsIgnoreCase("noReadInput");
    	
    	Config.initConfigWithConfigFile();
    	
        AmazonSimpleWorkflow swfService = Config.createSWFClient();
        String domain = Config.data.domain;

        final WorkflowWorker worker = new WorkflowWorker(swfService, domain, DECISION_TASK_LIST);
        worker.addWorkflowImplementationType(UnitTestWorkflowImpl.class);
        worker.start();

        System.out.println("Workflow Host Service Started...");

        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
			public void run() {
                try {
                    worker.shutdownAndAwaitTermination(1, TimeUnit.MINUTES);
                    System.out.println("Workflow Host Service Terminated...");
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        try
        {
        	if (shouldReadInput)
        	{
        		System.out.println("Please press any key to terminate service.");
        		System.in.read();
        	}
        	else
        	{
        		System.out.println("Waiting indefiniely.");
        		while(true);
        	}
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        System.exit(0);

    }

}
